package com.hy.lightning.ds.redis;

import java.util.Map;
import java.util.Map.Entry;
import java.util.concurrent.ConcurrentHashMap;

import com.hy.lightning.ds.RedisDataSource;

import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;

public class BaseRedisDataSource implements RedisDataSource {
	
	/**
	 * redis数据库连接池
	 */
	private static Map<String, JedisPool> jedisPool_map = new ConcurrentHashMap<>();
	
	private static volatile boolean isInitJedisPool = false;
	
	/**
	 * 初始化数据库连接池配置
	 */
	static {
		if(!isInitJedisPool) {
			for(Entry<String, RedisConf> entry : conf_map.entrySet()) {
				RedisConf redisConf = entry.getValue();
				if(redisConf != null) {
					JedisPool jedisPool = new JedisPool(redisConf.getJedisPoolConfig(), redisConf.getHost(), redisConf.getPort(), redisConf.getTimeout(), redisConf.getPassword());
					jedisPool_map.put(redisConf.getKey(), jedisPool);
				}
			}
			isInitJedisPool = true;
		}
		
	}
	
	
	@Override
	public Jedis getJedis(String key) {
		Jedis jedis = jedisPool_map.get(key).getResource();
		RedisConf redisConf = conf_map.get(key);
		jedis.select(redisConf.getIndex());
		return jedis;
	}

	@Override
	public void releasePoolAll() {
		for(Entry<String, JedisPool> entry : jedisPool_map.entrySet()) {
			JedisPool jedisPool = entry.getValue();
			if(jedisPool != null) {
				jedisPool.close();
			}
		}
	}

	@Override
	public void releasePool(String key) {
		JedisPool jedisPool = jedisPool_map.get(key);
		if(jedisPool != null) {
			jedisPool.close();
		}
	}
}
